<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

require_once 'MainPageWidget.php';
class NodeTagsWidget extends MainPageWidget {
	public $title = 'Облако тегов';
  public $from = 'node';
  public $communities = array();
  public $community_list = array();
  public $tdi = array();
  public $tdi_list = array();
  public $widget_view = 'WG_NodeTagsWidget';
  
	public function Render() {
    $user_oids = $this->getUserOIDs();
    
    $db_prefix = $this->ctx->store->db->db_prefix;
    
    if ( 'node' == $this->from ) {
      $sql = 'select (select count(*) FROM t_acl_tree as node ' .
      ' left join t_acl_tree as parent on parent.lft <= node.lft and parent.rgt >= node.rgt ' .
      ' left outer join t_acl_list on parent.id_object = t_acl_list.id_acl_tree ' .
      ' where node.id_object = ts.subject_oid ' .
      ' and t_acl_list.id_subject in ( ' . join(',', $user_oids) . ' ) ' .
      ' and t_acl_list.`action` in ("item_read") ' .
      " and t_acl_list.opt = 2) as disabled, t.oid, t.name from {$db_prefix}class_tag t " .
      " left join {$db_prefix}objects o on t.oid = o.oid " .
      " left join {$db_prefix}objects o2 on t.community_oid = o2.oid " .
      " left join {$db_prefix}tag_subject ts on t.oid = ts.tag_oid " .
      " left join {$db_prefix}objects o3 on o3.oid = ts.subject_oid " .
      " left join {$db_prefix}class_allfeed a on a.oid = ts.subject_oid " .
      ' where o.is_deleted = 0 and o2.is_deleted = 0 and o3.is_deleted = 0 ' .
      ' having `disabled` = 0 order by name';
    } else {
      $communityWhere = array();
      foreach ( $this->community_list as $community_oid ) {
        $tdi = $this->getTdiList( $community_oid );
        
        if ( !empty($tdi) ) {
          $tdi_list = array();
          
          foreach ( $this->tdi_list as $tdi_oid ) {
            foreach ($tdi as $val) {
              if ( $tdi_oid == $val['oid'] || 0 == $tdi_oid ) {
                $tdi_list[] = $tdi_oid;
                break;
              }
            }
          }
          
          $communityWhere[] = "(a.community_oid = {$community_oid} and a.tdi_oid in (" . join(',', $tdi_list) . '))';
        } else {
          $communityWhere[] = "a.community_oid = {$community_oid}";
        }
      }
      
      $community_string = '(' . join(' or ', $communityWhere) . ')';
      
      $sql = 'select (select count(*) FROM t_acl_tree as node ' .
      ' left join t_acl_tree as parent on parent.lft <= node.lft and parent.rgt >= node.rgt ' .
      ' left outer join t_acl_list on parent.id_object = t_acl_list.id_acl_tree ' .
      ' where node.id_object = ts.subject_oid ' .
      ' and t_acl_list.id_subject in ( ' . join(',', $user_oids) . ' ) ' .
      ' and t_acl_list.`action` in ("item_read") ' .
      " and t_acl_list.opt = 2) as disabled, t.oid, t.name from {$db_prefix}class_tag t " .
      " left join {$db_prefix}objects o on t.oid = o.oid " .
      " left join {$db_prefix}objects o2 on t.community_oid = o2.oid " .
      " left join {$db_prefix}tag_subject ts on t.oid = ts.tag_oid " .
      " left join {$db_prefix}objects o3 on o3.oid = ts.subject_oid " .
      " left join {$db_prefix}class_allfeed a on a.oid = ts.subject_oid " .
      " where o.is_deleted = 0 and o2.is_deleted = 0 and o3.is_deleted = 0 " .
      " and {$community_string} " .
      " having `disabled` = 0 order by name";
    }
    
    $result = $this->ctx->store->query($sql);
    
    if ( $result instanceof MysqlDBResult ) {
      $tags = array();
      $min_count = 0;
      $max_count;
      while ( $row = $result->next() ) {
        $tag = mb_strtolower($row['name']);
        $tags[$tag]['count']++;
        $tags[$tag]['name'] = $row['name'];
        
        if ($tags[$tag]['count'] > $max_count) {
          $max_count = $tags[$tag]['count'];
        }
        if ($tags[$tag]['count'] < $min_count) {
          $min_count = $tags[$tag]['count'];
        }
      }
      
      ksort($tags);
      
      $weights = 7;
      $range = $max_count - $min_count;
      
      foreach ( $tags as $key=>$val ) {
        $tags[$key]['weight'] =
          ($range)
          ? round(($val['count'] - $min_count) * ($weights - 1) / $range) + 1
          : round($weight / 2);
      }
      
      $this->content['tags'] = $tags;
    }
    
		return $this;
  }
	
  public function settingsForm() {
    if ( empty($this->community) ) {
      $rs = $this->ctx->store->find("objects where objects.type = :0 and objects.is_deleted=0 order by objects.ctime desc", array("fcommunity"));
  		while ($obj = $rs->next()) {
  			$this->community[] = array_merge($obj->data, array(
  				'oid' => $obj->id
  			));
  		}
    }
    
    foreach ( $this->community as $key=>$val ) {
      foreach ( $this->community_list as $oid ) {
        if ( $oid == $val['oid'] ) {
          $this->community[$key]['checked'] = true;
          break;
        }
      }
      $tdi_list = $this->getTdiList( $val['oid'] );
      
      foreach ($tdi_list as $index=>$tdi) {
        foreach ($this->tdi_list as $present) {
          if ( $present == $tdi['oid'] ) {
            $tdi_list[$index]['checked'] = true;
          } else if ( 0 == $present && isset($this->community[$key]['checked'])
          && $this->community[$key]['checked']) {
            $this->community[$key]['root_checked'] = true;
          }
        }
      }
      
      $this->community[$key]['tdi'] = $tdi_list;
    }
    
		if ( !isset($this->params) || !isset($this->params['title']) ) {
			$this->params['title'] = $this->title;
      $this->params['from'] = $this->from;
      $this->params['community'] = $this->community;
		}
    
		//return $this->params;
	}
  
  public function setParams( $params ) {
    foreach ( $params as $key=>$val ) {
      if ( isset($this->$key) ) {
        $this->$key = $val;
      }
    }
  }

  private function getUserOIDs() {
    $user_oids = array();
    
    if ( isset($this->ctx->mm->aa) && !empty($this->ctx->mm->aa) ) {
      $aa = $this->ctx->mm->aa;
      if ( isset($aa->acl_data['user_id']) && !empty($aa->acl_data['user_id']) ) {
        $user_oids[] = $aa->acl_data['user_id'];
      }
      if ( isset($aa->acl_data['role']['oid']) && !empty($aa->acl_data['role']['oid']) ) {
        $user_oids[] = $aa->acl_data['role']['oid'];
      }
    }
    return $user_oids;
  }
}